﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Alta.Class
{
    public enum AppMode
    {
        AUTO, MANUAL, DEBUG
    }
    [Serializable]
    public class setting
    {
        public string host = "localhost";
        public string user = "root";
        public string pass = "";
        public string database = "alta_camera";

        public AppMode mode = AppMode.AUTO;

        public static void write(setting s, string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new Exception("File Name Không được để trống.");
            FileInfo inf = new FileInfo(fileName);          
            System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(setting));
            if (inf.Exists)
            {
                while (inf.IsFileLocked()) { Console.WriteLine("wait..."); }
                using (Stream stream = File.Open(fileName, FileMode.Truncate))
                {
                    writer.Serialize(stream, s);
                }
            }
            else
            {
                using (Stream stream = File.Open(fileName, FileMode.CreateNew))
                {
                    writer.Serialize(stream, s);
                }
            }
        }

        public static setting read(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new Exception("File Name Không Được Bỏ Trống");
            FileInfo inf = new FileInfo(fileName);
            if(!inf.Exists)
            {
                write(new setting(), fileName);
                return new setting();
            }
            else
            {
                System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(setting));
                while (inf.IsFileLocked()) { Console.WriteLine("Wait..."); }
                using (Stream stream = File.Open(fileName, FileMode.Open))
                {
                    return (setting)reader.Deserialize(stream);
                }
            }
        }
    }
}
